import { ref, reactive } from 'vue';

export function useTableMixin(tableConfig) {

  const apiGetTableData = tableConfig.apiGetTableData
  // true 表示可以发送请求， false 表示不发送请求
  const tableApiFlag = ref(true);
  // 分页
  const page = reactive({
    total: 0,
    pageNo: 1,
    pageSize: 20
  });
  const selection = ref([])

  /**
   * @description: 修复 pageNo 不为 1，修改 pageSize，重复请求的 bug
   */
  function handleTableMixinSearch() {
    if (page.pageNo === 1) {
      apiGetTableData();
    } else {
      page.pageNo = 1;
    }
  }
  /**
   * @description: 更改页面展示条数
   * @param {Number} _pageSize 页面条数
   */
  function handleSizeChange(_pageSize) {
    page.pageSize = _pageSize;
    handleTableMixinSearch();
  }
  /**
   * @description: 更改当前页数
   * @param {Number} _pageNo 当前页数
   */
  function handleCurrentChange(_pageNo) {
    page.pageNo = _pageNo;
    apiGetTableData();
  }

  /**
   * @description: 表格选择项改变
   * @param {Array} _selection 当前选择项
   */
  function handleSelectionChange(_selection) {
    selection.value = _selection;
  }
  /**
   * @description: 刷新页面   避免多次重复请求
   */
  function refreshTable() {
    if (page.pageSize === 20) {
      handleTableMixinSearch();
    } else {
      page.pageSize = 20;
    }
  }

  return {
    page,
    tableApiFlag,
    selection,
    handleTableMixinSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    refreshTable
  }
}

export default useTableMixin
